<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\AdminUsersRequest;
use App\Model\AdminUsers;
use App\Model\Roles;
use Illuminate\Http\Request;
use App\Repositories\AdminUsersRepository;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    protected $fields = [
        'name' => '',
        'email' => '',
        'roles' => [],
    ];
    private $adminEntity;
    public function __construct(Request $req,AdminUsersRepository $admin){
        $this->req = $req;
        $this->adminEntity = $admin;
        view()->share('fatherKey','user');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if ($this->req->ajax()) {
            $data = array();
            $data['draw'] = $this->req->get('draw');
            $start = $this->req->get('start');
            $length = $this->req->get('length');
            $order = $this->req->get('order');
            $columns = $this->req->get('columns');
            $search = $this->req->get('search');
            $data['recordsTotal'] = AdminUsers::count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = AdminUsers::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('email', 'like', '%' . $search['value'] . '%');
                })->count();
                $data['data'] = User::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('email', 'like', '%' . $search['value'] . '%');
                })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = AdminUsers::count();
                $data['data'] = AdminUsers::skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        return view('admin.user.index')->with('childKey','userList');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['rolesAll'] = Roles::all()->toArray();
        return view('admin.user.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdminUsersRequest $due)
    {
        $data = $due->all();
        $res = $this->adminEntity->create($data);
        if($res !== false){
            return redirect('/admin/user')->withSuccess('添加成功！');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = AdminUsers::find((int)$id);
        if (!$user) return redirect('/admin/user')->withErrors("找不到该用户!");
        $roles = [];
        if ($user->roles) {
            foreach ($user->roles as $v) {
                $roles[] = $v->id;
            }
        }
        $user->roles = $roles;
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $user->$field);
        }
        $data['rolesAll'] = Roles::all()->toArray();
        $data['id'] = (int)$id;
        return view('admin.user.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        $data = $this->req->all();
        unset($data['repassword']);
        unset($data['roles']);
        $res = $this->adminEntity->update($data,$id);
        if($res !== false){
            return redirect('/admin/user/index')->withSuccess('编辑成功！');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $tag = AdminUsers::find((int)$id);
        if ($tag && $tag->id != 1) {
            $tag->delete();
        } else {
            return redirect()->back()
                ->withErrors("删除失败");
        }

        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
